import 'dart:convert';
import 'dart:ui';

import 'package:common_utils/common_utils.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:yinshui_caiying/http/api_project.dart';
import 'package:yinshui_caiying/http/http.dart';
import 'package:yinshui_caiying/model/image_list_result_model.dart';
import 'package:yinshui_caiying/model/image_model.dart';
import 'package:yinshui_caiying/model/image_result_model.dart';
import 'package:yinshui_caiying/model/params_model.dart';
import 'package:yinshui_caiying/model/projectItem_model.dart';
import 'package:yinshui_caiying/model/result_model.dart';
import 'package:yinshui_caiying/pages/project/project_create.dart';
import 'package:yinshui_caiying/services/common_services.dart';
import 'package:yinshui_caiying/utils/colors.dart';
import 'package:yinshui_caiying/utils/inputformatter.dart';
import 'package:yinshui_caiying/widgets/action_text_button.dart';
import 'package:yinshui_caiying/widgets/appbar.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:yinshui_caiying/widgets/base_scaffold.dart';
import 'package:yinshui_caiying/widgets/form/form_with_adPicker.dart';
import 'package:yinshui_caiying/widgets/form/form_with_singlePicker.dart';
import 'package:yinshui_caiying/widgets/form/form_with_textField.dart';
import 'package:yinshui_caiying/widgets/loading.dart';
import 'package:map_launcher/map_launcher.dart';
import 'package:yinshui_caiying/widgets/modal_title.dart';
import 'package:yinshui_caiying/widgets/my_dialog.dart';
import 'package:yinshui_caiying/widgets/noData.dart';
import 'package:yinshui_caiying/widgets/picker/models/ad_list_result_model.dart';
import 'package:yinshui_caiying/widgets/picker/models/pickerItem_model.dart';
import 'package:yinshui_caiying/widgets/picker/pickers.dart';

class ProjectListPage extends StatelessWidget {
  ProjectLsitPageController vm = Get.put(ProjectLsitPageController());
  CommonService commonService = Get.find();
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  @override
  Widget build(BuildContext context) {
    vm.context = context;
    return BaseScaffold(
      isTwiceBack: false,
      appBar: BackTitleBar(
        title: '工程列表',
        hasback: true,
        action: Row(
          children: [
            ActionTextButton(
                title: '报警',
                width: 70.w,
                height: 34.h,
                onPressed: () {
                  Get.toNamed('/alarm',
                      arguments: ParamsModel(
                          id: 0, ad_id: vm._adId, ad_name: vm._adName.value));
                }),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        child: Text(
          '创建',
          style: TextStyle(color: Colors.white, fontSize: 46.sp),
        ),
        onPressed: () {
          Get.toNamed('/project_create');
        },
        backgroundColor: MyColors.main,
      ),
      body: SafeArea(
        child: Column(
          children: [menuBar(), searchBar(), Obx(() => projectList())],
        ),
      ),
    );
  }

  ///按钮菜单栏
  Widget menuBar() {
    return Container(
      width: 1.sw,
      height: 140.h,
      decoration: BoxDecoration(color: Colors.white),
      child: Row(
        children: [
          Expanded(
            child: TextButton(
                onPressed: () {
                  Pickers.showSinglePicker(
                    data: vm.commonService.projectTypeList,
                    selectData: vm._projectType.value.value,
                    onConfirm: vm._searchProjectType,
                  );
                },
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Text(
                      vm._projectType.value.name,
                      style: TextStyle(color: Colors.black),
                    ),
                    Container(
                      margin: EdgeInsets.only(left: 24.w),
                      child: Icon(
                        Icons.expand_more,
                        color: Color.fromRGBO(204, 204, 204, 1),
                        size: 30.w,
                      ),
                    ),
                  ],
                )),
          ),
          Container(
            width: 1.w,
            color: Color.fromRGBO(204, 204, 204, 1),
          ),
          Expanded(
            child: TextButton(
                onPressed: () {
                  Pickers.showAdPicker(
                      selectData: vm._adId,
                      data: vm.commonService.adList,
                      onConfirm: (value) {
                        vm._searchProjectAdId(value);
                      },
                      onAll: (value) {
                        vm._searchProjectAdId(value);
                      });
                },
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Obx(() => Text(
                          vm._adName.value,
                          style: TextStyle(color: Colors.black),
                        )),
                    Container(
                      margin: EdgeInsets.only(left: 24.w),
                      child: Icon(
                        Icons.expand_more,
                        color: Color.fromRGBO(204, 204, 204, 1),
                        size: 30.w,
                      ),
                    ),
                  ],
                )),
          )
        ],
      ),
    );
  }

  ///搜索栏
  Widget searchBar() {
    return Container(
      width: 1.sw,
      height: 150.h,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        // crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Container(
            padding: EdgeInsets.fromLTRB(37.w, 27.h, 37.w, 24.h),
            width: 989.w,
            height: 98.h,
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Icon(
                  Icons.search,
                  size: 48.w,
                  color: Color.fromRGBO(204, 204, 204, 1),
                ),
                SizedBox(
                  width: 33.w,
                ),
                Expanded(
                    child: TextField(
                  controller: vm.keywordsController,
                  style: TextStyle(height: 3.h, fontSize: 36.sp),
                  decoration: InputDecoration.collapsed(
                    hintText: '输入工程相关关键字',
                  ),
                  onChanged: (value) {
                    vm._searchKeyWords(value);
                  },
                ))
              ],
            ),
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(48.w),
                border: Border.all(
                  color: Color.fromRGBO(204, 204, 204, 1),
                )),
          )
        ],
      ),
    );
  }

  ///工程列表
  Widget projectList() {
    return Expanded(
        child: RefreshIndicator(
      onRefresh: vm._onRefresh,
      child: vm._projectList.length > 0
          ? ListView.builder(
              controller: vm._scrollController,
              itemCount: vm._projectList.length,
              physics: AlwaysScrollableScrollPhysics(),
              itemBuilder: (context, index) {
                return Column(children: [
                  projectItem(index),
                  SizedBox(
                    height: 20.h,
                  ),
                  _showMore(index)
                ]);
              },
            )
          : vm._flag
              ? NoDataWidget()
              : LoadingWidget(),
    ));
  }

  final SlidableController slidableController = SlidableController();

  ///工程项目视图
  ///
  ///[index]为该项目的索引
  Widget projectItem(index) {
    ProjectItemModel item = vm._projectList[index];
    final isExpanded = false.obs;
    TextStyle subTitleStyle =
        TextStyle(color: Color.fromRGBO(96, 96, 96, 1), fontSize: 36.sp);
    return GestureDetector(
      onDoubleTap: () {
        Get.toNamed('/water_user_list',
            arguments: ParamsModel(
                params: '', id: item.id, name: item.name, ad_id: item.adId));
      },
      child: Container(
        // padding: EdgeInsets.fromLTRB(0, 37.h, 0, 0),
        color: Colors.white,
        child: Column(
          children: [
            Slidable(
                key: Key(item.id.toString()),
                controller: slidableController,
                actionPane: SlidableDrawerActionPane(),
                actionExtentRatio: 0.12,
                child: Column(
                  children: [
                    ///面版头部标题区域
                    Container(
                      width: 1.sw,
                      // color: Colors.red,
                      height: 143.h,
                      padding: EdgeInsets.fromLTRB(51.w, 0, 41.w, 0),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Row(
                            children: [
                              Container(
                                width: 31.w,
                                height: 33.h,
                                child: Image.asset(
                                  'assets/images/list/icon-flag-green.png',
                                  fit: BoxFit.fill,
                                ),
                              ),
                              InkWell(
                                // onTap: () {
                                //   Get.toNamed('/water_user_list',
                                //       arguments: ParamsModel(
                                //           params: '',
                                //           id: item.id,
                                //           name: item.name));
                                // },
                                child: Container(
                                  margin: EdgeInsets.only(left: 23.w),
                                  child: Text(item.name,
                                      style: TextStyle(
                                          color: Colors.black,
                                          fontSize: 42.sp,
                                          fontWeight: FontWeight.w500)),
                                ),
                              ),
                            ],
                          ),
                          Container(
                            width: 63.w,
                            height: 63.w,
                            child: InkWell(
                              onTap: () {
                                print("导航到");
                                vm._linkToMap(index);
                              },
                              child: Image.asset(
                                  'assets/images/list/icon-to-map.png'),
                            ),
                          )
                        ],
                      ),
                    ),

                    ///面板内容固定区域
                    Container(
                      width: 1.sw,
                      height: 170.h,
                      padding: EdgeInsets.fromLTRB(103.2.w, 0, 41.w, 35.h),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Row(
                            children: [
                              Container(
                                width: 580.w,
                                child: Text(
                                  '工程类型：${item.pjtName}',
                                  style: subTitleStyle,
                                ),
                              ),
                              Expanded(
                                  child: Text(
                                '井眼深度：${item.ziduan1}m',
                                style: subTitleStyle,
                              ))
                            ],
                          ),
                          Row(
                            children: [
                              Container(
                                width: 580.w,
                                child: Text(
                                  '水表数量：${item.meterNum}',
                                  style: subTitleStyle,
                                ),
                              ),
                              Expanded(
                                  child: Text(
                                '井眼内径：${item.ziduan3}m',
                                style: subTitleStyle,
                              ))
                            ],
                          )
                        ],
                      ),
                    ),

                    ///面板内容伸缩区域
                    Obx(() => AnimatedContainer(
                          padding: EdgeInsets.fromLTRB(103.w, 0, 103.w, 46.h),
                          width: 1.sw,
                          // color: Colors.orange,
                          duration: Duration(milliseconds: 200),
                          height: isExpanded.value ? 356.h : 0.h,
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Expanded(
                                  child: Container(
                                child: Text(
                                  '经纬度：${vm._projectList[index].longitude}，${vm._projectList[index].latitude}',
                                  style: subTitleStyle,
                                ),
                                margin: EdgeInsets.only(bottom: 40.h),
                              )),
                              Expanded(
                                  child: Container(
                                child: Text(
                                  '归属地：${vm._projectList[index].adName}',
                                  style: subTitleStyle,
                                ),
                              )),
                              Expanded(
                                  flex: 1,
                                  child: vm._projectList[index].imageList
                                              .length >
                                          0
                                      ? ListView.builder(
                                          itemCount: vm._projectList[index]
                                              .imageList.length,
                                          scrollDirection: Axis.horizontal,
                                          itemBuilder: (context, num) {
                                            return Container(
                                              width: 140.w,
                                              height: 140.w,
                                              margin: EdgeInsets.only(
                                                  left: num == 0 ? 0 : 25.w),
                                              child: InkWell(
                                                child: Image.network(vm
                                                    ._projectList[index]
                                                    .imageList[num]
                                                    .path),
                                                onTap: () {
                                                  MyDialog.openImageView(
                                                      num,
                                                      vm._projectList[index]
                                                          .imageList);
                                                },
                                              ),
                                            );
                                          })
                                      : Container(
                                          child: Text('暂无图片数据',
                                              style: subTitleStyle),
                                        ))
                            ],
                          ),
                        )),
                  ],
                ),

                ///侧滑区域
                secondaryActions: [
                  IconSlideAction(
                    // caption: '编辑',
                    color: Color.fromRGBO(11, 193, 80, 1),
                    iconWidget: Container(
                      // width: 50.w,
                      // height: 50.w,
                      // color: Colors.white,
                      child: Text(
                        '编辑',
                        style: TextStyle(color: Colors.white, fontSize: 36.sp),
                      ),
                    ),
                    onTap: () {
                      vm._selectProjectItem(vm._projectList[index]);
                      _showEditProjectDialog();
                    },
                  ),
                  IconSlideAction(
                    color: Color.fromRGBO(241, 15, 15, 1),
                    iconWidget: Container(
                      child: Text(
                        '删除',
                        style: TextStyle(color: Colors.white, fontSize: 36.sp),
                      ),
                    ),
                    onTap: () {
                      vm._showDelProjectDialog(index);
                    },
                  )
                ]),
            //底部收起展开栏
            Container(
              height: 100.h,
              // color: Colors.green,
              margin: EdgeInsets.only(left: 104.w, right: 104.w),
              decoration: BoxDecoration(
                  border: Border(
                      top: BorderSide(
                          width: 1.w, color: Color.fromRGBO(0, 0, 0, 0.2)))),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  TextButton(
                      style: ButtonStyle(
                          padding: MaterialStateProperty.all(EdgeInsets.zero)),
                      onPressed: () {
                        if (!isExpanded.value) {
                          vm._getProjectImageData(
                              index, vm._projectList[index]);
                        }
                        isExpanded.toggle();
                      },
                      child: Row(
                        children: [
                          Obx(() => Text(
                                isExpanded.value ? '收起' : '展开',
                                style: TextStyle(
                                  color: Color.fromRGBO(96, 96, 96, 0.6),
                                  fontSize: 36.sp,
                                ),
                              )),
                          Container(
                            margin: EdgeInsets.only(left: 20.w),
                            child: Obx(() => Icon(
                                  isExpanded.value
                                      ? Icons.expand_less
                                      : Icons.expand_more,
                                  size: 30.w,
                                  color: Color.fromRGBO(204, 204, 204, 1),
                                )),
                          )
                        ],
                      ))
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  ///列表状态
  ///
  ///[index]为项目的索引
  Widget _showMore(index) {
    if (vm._hasMore.value) {
      if (index == vm._projectList.length - 1) {
        return LoadingWidget();
      } else {
        return Text('');
      }
    } else {
      return (index == vm._projectList.length - 1)
          ? Text('我是有底线的',
              style: TextStyle(
                color: Color.fromRGBO(119, 119, 119, 0.6),
                fontSize: 34.sp,
              ))
          : Text('');
    }
  }

  ///编辑弹窗
  _showEditProjectDialog() {
    showModalBottomSheet(
        context: vm.context,
        backgroundColor: Colors.transparent,
        isScrollControlled: true,
        builder: (context) {
          return Container(
              height: 0.8.sh,
              width: 1.sw,
              padding: EdgeInsets.fromLTRB(77.w, 53.h, 63.w, 50.h),
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(30.w),
                      topRight: Radius.circular(30.w))),
              child: Column(children: [
                ModalTitle(
                    title: '工程信息修改',
                    margin: 0,
                    onPressed: () {
                      Navigator.pop(context);
                    }),
                Expanded(
                    child: Form(
                        key: _formKey, //设置globalKey，用于后面获取FormState
                        child: Container(
                          // height: 0.5.sh,
                          width: 1.sw,
                          child: ListView(children: [
                            FormSinglePicker(
                              title: '工程类型',
                              onConfirm: (value) {},
                              dataList: vm.commonService.projectTypeList,
                              value: vm._projectTypeId,
                            ),
                            FormAdPicker(
                                title: '归属地',
                                onConfirm: vm.adIdCof,
                                dataList: vm.commonService.adList,
                                name: vm.ad_name,
                                value: vm.ad_id),
                            FormInput(
                                title: '工程名称',
                                placeholder: '请输入工程名称',
                                onChanged: (value) {
                                  vm._projectName.value = value;
                                },
                                initValue: vm._projectName.value,
                                request: true),
                            FormInput(
                              title: '表井编号',
                              placeholder: '请输入表井编号',
                              onChanged: (value) {
                                vm._projectCode.value = value;
                              },
                              initValue: vm._projectCode.value,
                              request: true,
                            ),
                            FormInput(
                              title: '井眼深度',
                              placeholder: 'm',
                              inputFormatters: [InputFormatter.xiaoshu],
                              keyboardType: TextInputType.number,
                              unit: 'm',
                              onChanged: (value) {
                                vm._projectDeepLength.value =
                                    NumUtil.getDoubleByValueStr(value)!;
                              },
                              initValue: vm._projectDeepLength.value.toString(),
                            ),
                            // FormInput(
                            //     title: '水表通径',
                            //     placeholder: 'm',
                            //     inputFormatters: [InputFormatter.xiaoshu],
                            //     keyboardType: TextInputType.number,
                            //     unit: 'm',
                            //     onChanged: (value) {
                            //       vm._projectOutRadius.value =
                            //           NumUtil.getDoubleByValueStr(value)!;
                            //     },
                            //     initValue:
                            //         vm._projectOutRadius.value.toString()),
                            FormInput(
                                title: '井口内径',
                                placeholder: 'm',
                                inputFormatters: [InputFormatter.xiaoshu],
                                keyboardType: TextInputType.number,
                                unit: 'm',
                                onChanged: (value) {
                                  vm._projectInRadius.value =
                                      NumUtil.getDoubleByValueStr(value)!;
                                },
                                initValue:
                                    vm._projectInRadius.value.toString()),
                            SizedBox(
                              height: 50.h,
                            ),
                            _saveButton(),
                          ]),
                        )))
              ]));
        });
  }

  ///保存按钮
  ///保存按钮
  Widget _saveButton() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Container(
          width: 724.w,
          height: 145.h,
          child: ElevatedButton(
            onPressed: () {
              if (_formKey.currentState!.validate()) {
                print('提交成功');

                vm._saveForm();
              }
            },
            child: Text('保  存'),
            style: ButtonStyle(
                foregroundColor: MaterialStateProperty.all(Colors.white),
                backgroundColor: MaterialStateProperty.all(MyColors.main),
                shape: MaterialStateProperty.all(RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(Radius.circular(72.w)))),
                textStyle: MaterialStateProperty.all(TextStyle(
                  fontSize: 48.sp,
                  fontWeight: FontWeight.w500,
                ))),
          ),
        )
      ],
    );
  }
}

///工程列表页控制器
class ProjectLsitPageController extends GetxController {
  CommonService commonService = Get.find();

  late BuildContext context;

  ///下滑判断开关
  bool _flag = true;

  ///页码
  int _page = 1;

  ///一页多少个
  int _pageSize = 10;

  ///是否有更多
  final _hasMore = true.obs;

  ///是否有数据
  final _hasData = true.obs;

  ///行政区划名称
  final _adName = '行政区划'.obs;

  ///行政区划id
  int? _adId = 0;

  ///模糊查询
  String keywords = '';

  ///工程名称
  final _projectName = "".obs;

  ///表井编号
  final _projectCode = ''.obs;

  ///井眼深度
  final _projectDeepLength = 0.0.obs;

  ///井直径
  final _projectOutRadius = 0.0.obs;

  ///井内径
  final _projectInRadius = 0.0.obs;

  ///行政区划表单id
  final ad_id = Rx<int>(-1);

  ///行政区划表单name
  final ad_name = ''.obs;

  ///工程id
  int? _pj_id;

  ///工程类型表单id
  final _projectTypeId = PickerItemModel().obs;

  ///编辑项目在列表中的索引
  int index = 0;

  ///行政区划编码
  String ad_code = '';

  ///处理行政区划反填值
  adIdCof(List<AdItemModel> data) {
    ad_name.value = data.map((e) => e.name).toList().join('-');
    ad_id.value = data[data.length - 1].id;
  }

  ///模糊查询的控制器
  TextEditingController keywordsController = TextEditingController();

  ///工程类型id
  final _projectType = PickerItemModel().obs;

  ///ListView滑动控制器
  ScrollController _scrollController = ScrollController();

  ///工程列表
  final _projectList = <ProjectItemModel>[].obs;

  @override
  void onInit() async {
    if (Get.arguments != null) {
      keywords = Get.arguments.params;
      keywordsController.text = Get.arguments.params;
      if (Get.arguments.ad_code != null) {
        ad_code = Get.arguments.ad_code;
      }
    }

    _projectType(commonService.projectTypeList[0]);
    final availableMaps = await MapLauncher.installedMaps;
    availableMaps.forEach((element) {
      print(element.mapName);
    });
    print(availableMaps);

    ///初始化时先拿一次数据
    getProjectListData();

    ///监听ListView滚动事件

    _scrollController.addListener(() {
      if (_scrollController.position.pixels >
          _scrollController.position.maxScrollExtent - 20) {
        if (_flag && _hasMore.value) {
          getProjectListData();
        }
      } else {}
    });
    super.onInit();
  }

  ///获取工程列表
  Future<void> getProjectListData() async {
    _flag = false;

    try {
      var res = await Http().post(
        ApiProject.PROJECT_LIST,
        data: {
          'params': {
            "type_id": _projectType.value.value,
            "ad_id": _adId,
            "params": keywords,
          },
          "ad_code": ad_code,
          'paginate': {"total": 0, "page": _page, 'per_page': _pageSize},
        },
      );
      ProjectListResultModel result = ProjectListResultModel.fromJson(res);
      if (result.code == 200) {
        _projectList.addAll(result.content.data);
        _page++;
        _flag = true;
        if (result.content.data.length < _pageSize) {
          _hasMore.value = false;
        }
        if (_projectList.length == 0) {
          _hasData.value = false;
        } else {
          _hasData.value = true;
        }
      }
    } catch (e) {
      print(e.toString());
    }
  }

  ///获取工程图片

  Future<void> _getProjectImageData(int index, ProjectItemModel item) async {
    var res = await Http().post(ApiProject.PROJECT_IMAGE_LIST, data: {
      'params': {'id': item.id},
      "paginate": {"total": 0, "page": 1, "per_page": 100},
    });
    ImageListResultModel result = ImageListResultModel.fromJson(res);
    if (result.code == 200) {
      item.imageList.clear();
      result.content.data.forEach((element) {
        item.imageList.add(ImageModel(id: element.id, path: element.path));
      });
    }
  }

  ///下拉刷新
  Future<void> _onRefresh() async {
    resetParams();

    //重新请求数据
    await getProjectListData();
  }

  ///打开导航
  _linkToMap(index) async {
    Coords coords =
        Coords(_projectList[index].latitude, _projectList[index].longitude);
    String title = _projectList[index].name;
    int zoom = 16;
    var hasgaode = await MapLauncher.isMapAvailable(MapType.amap);
    var hasbaidu = await MapLauncher.isMapAvailable(MapType.baidu);
    if (hasgaode != null && hasgaode) {
      ///如果有高德优先打开高德
      await MapLauncher.showMarker(
        mapType: MapType.amap,
        coords: coords,
        title: title,
        zoom: zoom,
        description: '工程位置',
      );
    } else if (hasbaidu != null && hasbaidu) {
      ///如果没有高德则去找百度
      await MapLauncher.showMarker(
        mapType: MapType.baidu,
        coords: coords,
        title: title,
        zoom: zoom,
        description: '工程位置',
      );
    } else {
      ///都没有则提示未安装app
      SmartDialog.showToast('手机未安装任何地图应用');
    }
  }

  ///重置查询数据
  resetParams() {
    //重置分页数
    _page = 1;

    //重置数据
    _projectList.clear();

    //滚动条回到顶部
    if (_projectList.length > 0) {
      _scrollController.jumpTo(0);
    }

    //重置hasmore
    _hasMore.value = true;
  }

  ///模糊搜索事件
  Future<void> _searchKeyWords(value) async {
    keywords = value;
    resetParams();

    //重新请求数据
    await getProjectListData();
  }

  ///按工程类型查询
  _searchProjectType(PickerItemModel value) async {
    print(value);
    _projectType(value);
    resetParams();

    ///重新请求数据
    await getProjectListData();
  }

  ///按行政区划查询
  _searchProjectAdId(dynamic data) async {
    resetParams();

    if (data == null) {
      _adName.value = '全部';
      _adId = null;
    } else {
      _adName.value = data[data.length - 1].name;
      _adId = data[data.length - 1].id;
    }

    ///重新请求数据
    await getProjectListData();
  }

  ///选择工程
  _selectProjectItem(ProjectItemModel value) {
    _pj_id = value.id;
    _projectName.value = value.name;
    ad_id.value = value.adId;
    ad_name.value = value.adName;
    _projectCode.value = value.ziduan4;
    _projectDeepLength.value = NumUtil.getDoubleByValueStr(value.ziduan1)!;
    _projectOutRadius.value = NumUtil.getDoubleByValueStr(value.ziduan2)!;
    _projectInRadius.value = NumUtil.getDoubleByValueStr(value.ziduan3)!;
    _projectTypeId.update((val) {
      val!.name = value.pjtName;
      val.value = value.pjtId;
    });
  }

  ///修改工程
  _saveForm() async {
    if (ad_id.value == null || ad_id.value == -1) {
      SmartDialog.showToast('请选择行政区划');
      return false;
    }
    ;
    MyDialog.showLoading(msg: '修改工程...');
    try {
      var res = await Http().put(ApiProject.PROJECT_EDIT, data: {
        'pj_id': {'id': _pj_id},
        "data": {
          "name": _projectName.value,
          "ad_id": ad_id.value,
          "type_id": _projectTypeId.value.value,
        },
        "ac_data": {
          "ziduan1": _projectDeepLength.value.toString(),
          "ziduan2": _projectOutRadius.value.toString(),
          "ziduan3": _projectInRadius.value.toString(),
          "ziduan4": _projectCode.value
        },
      });
      SmartDialog.dismiss();
      ResultModel result = ResultModel.fromJson(res);
      if (result.code == 200) {
        SmartDialog.showToast('工程修改成功');
        Get.back();
        resetParams();

        ///重新请求数据
        await getProjectListData();
        // _scrollController.jumpTo(index);
        ///更新成功
      } else {
        ///更新失败
      }
    } catch (e) {
      SmartDialog.dismiss();
    }
  }

  ///删除工程
  _deleteProject(index, item) async {
    List<int> ids = [item.id];
    MyDialog.showLoading(msg: '删除中...');
    var res =
        await Http().delete(ApiProject.PROJECT_DELETE, data: {'ids': ids});
    SmartDialog.dismiss();
    ResultModel result = ResultModel.fromJson(res);
    if (result.code == 200) {
      _projectList.removeAt(index);
      SmartDialog.showToast('删除成功');
    } else {
      SmartDialog.showToast(result.message);
    }
  }

  ///删除弹窗
  _showDelProjectDialog(index) {
    MyDialog.confirmDialog(
        title: '删除',
        desc: '是否确定删除此项？',
        onConfirm: () {
          SmartDialog.dismiss();
          _deleteProject(index, _projectList[index]);
        });
  }
}
